﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;

namespace ServerMonitor
{
    public class SimpleHttpListener
    {
        private ProcessRequestHandler ProcessRequest;
        public void SetProcessRequest(ProcessRequestHandler handler)
        {
            this.ProcessRequest = handler;
        }

        public void Run()
        {
            // 检查系统是否支持
            if (!HttpListener.IsSupported)
            {
                throw new System.InvalidOperationException(
                    "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统！");
            }
            // 注意前缀必须以 / 正斜杠结尾
            string[] prefixes = new string[] { "http://localhost:49152/" };
            // 创建监听器.
            HttpListener listener = new HttpListener();
            // 增加监听的前缀.
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }
            // 开始监听
            listener.Start();
            Console.WriteLine("监听中...");
            while (true)
            {
                // 注意: GetContext 方法将阻塞线程，直到请求到达
                HttpListenerContext context = listener.GetContext();
                // 取得请求对象
                HttpListenerRequest request = context.Request;
                Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);

                // 取得回应对象
                HttpListenerResponse response = context.Response;

                // 取得回应流
                using (System.IO.TextWriter writer =
                    new System.IO.StreamWriter(response.OutputStream))
                {
                    string path = System.IO.Path.GetFileName(request.Url.AbsolutePath);

                    // 先输出到内存流中，以便查看生成的内容
                    System.IO.StringWriter sw = new System.IO.StringWriter();

                    // 通过委托调用 ASP.NET 服务器处理
                    this.ProcessRequest(
                        path,
                        request.Url.Query,
                        sw
                        );

                    // 获取 ASP.NET 处理的结果
                    string content = sw.ToString();
                    sw.Close();

                    Console.WriteLine(content);

                    response.ContentLength64
                        = System.Text.Encoding.UTF8.GetByteCount(content);
                    response.ContentType = "text/html; charset=UTF-8";
                    writer.Write(content);

                    Console.WriteLine("\r\nProcess Ok.\r\n");
                }

                if (Console.KeyAvailable)
                    break;
            }
            // 关闭服务器
            listener.Stop();

        }
    }
}